import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import getuser from '../../../../atoms/getuser';
import { tbcurriculums } from '../../../../atoms/db';

const logger = anylogger('pages/api/weapp/teacher/courses.api');

interface IData {
	section: number;
	mon: {
		name: string;
		id: string;
	}[];
	tue: {
		name: string;
		id: string;
	}[];
	wen: {
		name: string;
		id: string;
	}[];
	thu: {
		name: string;
		id: string;
	}[];
	fri: {
		name: string;
		id: string;
	}[];
	sat: {
		name: string;
		id: string;
	}[];
	sun: {
		name: string;
		id: string;
	}[];
}


type Result = IData[];

type Message = {
}

/**
 * 获取当前教师一周全部的课程
 */
const handler = an48<Result>();

handler.get(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);

		// const user = await getuser(req);
		// if (!user) {
		// 	console.error('无法获取到教师登录信息');
		// 	res.status(200).json([]);
		// 	return;
		// }

		// 获取当前教师全部的课程信息
		const all = await tbcurriculums()
			.select('*')
			/*应为 user.id */
			.where({
				teacher_id: 'T001'
			})
			.orderBy('week', 'asc')
			.orderBy('start_section');
		// 以周为字段（列），以节次为记录（行）处理数据
		// 为了提升数据处理效率，将数据使用Map处理一次,key为周
		const allmap = all.reduce((map, it) => {
			const data = map.get(it.week) || [];
			data.push(it);
			return map.set(it.week, data);
		}, new Map<number, ITbcurriculums[]>());
		// 现在我们已经简单处理了一次数据，可以进行数据整合了
		const sections = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
		const data = sections.map((it) => {
			// const weeks = [1, 2, 3, 4, 5, 6, 0];
			return {
				section: it,
				mon: getcurriculumname(it, allmap.get(1)),
				tue: getcurriculumname(it, allmap.get(2)),
				wen: getcurriculumname(it, allmap.get(3)),
				thu: getcurriculumname(it, allmap.get(4)),
				fri: getcurriculumname(it, allmap.get(5)),
				sat: getcurriculumname(it, allmap.get(6)),
				sun: getcurriculumname(it, allmap.get(0))
			};
		});

		res.status(200).json(data);

	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json([]);
	}
});

function getcurriculumname(section: number, curriculums: ITbcurriculums[]) {
	return (curriculums || []).filter((it) => {
		return it.start_section <= section && it.end_section >= section;
	}).map((it) => {
		return { name: it.coursename, id: it.course_id };
	});
}

export const config = {} as PageConfig;

export default handler;
